#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import wsgiref.handlers
import cgi
import re
import datetime
import base64
import urllib
import os

from datetime import *

from google.appengine.ext import webapp
from google.appengine.api import urlfetch
from google.appengine.ext import db
from google.appengine.api import memcache

from google.appengine.ext.webapp import template

from xml.etree.ElementTree import fromstring

from database import *

class MainHandler(webapp.RequestHandler):
  def get(self):
    
    template_values = {
      'shows': BroadcastShow.all().order("-pubDate").fetch(10)
    }
    
    path = os.path.join(os.path.dirname(__file__), 'template/index.html')
    self.response.out.write(template.render(path, template_values))


class Page(webapp.RequestHandler):
  def get(self):
    page = int(self.request.get('p'))
    count = self.request.get('c')
    if(count == ''):
      count = 10
    else:
      count = int(self.request.get('c'))
    
    template_values = {
      'shows': BroadcastShow.all().order("-pubDate").fetch(count, page),
      'back': (page + 1),
      'next': (page - 1)
    }
    
    path = os.path.join(os.path.dirname(__file__), 'template/page.html')
    self.response.out.write(template.render(path, template_values))

#参考URL http://osima.jp/google/gae-remove-datastore.html
class RemoveOld(webapp.RequestHandler):
  def get(self) :
    list=BroadcastShow.all().filter("pubDate <",datetime.today() - timedelta(30)).fetch(50)
    
    if len(list)<1:
      self.response.out.write( 'OK remove all data.' )
      return
    
    for c in list:
      c.delete()
    
    self.response.out.write( '<html>' )
    self.response.out.write( '<head>' )
    self.response.out.write( '<meta http-equiv="REFRESH" content="10;URL=/RemoveOld">')
    self.response.out.write( '</head>' )
    self.response.out.write( '<body>' )
    self.response.out.write( 'Again after 10seconds.' )
    self.response.out.write( '</body>' )
    self.response.out.write( '</html>' )

def main():
  application = webapp.WSGIApplication( [('/', MainHandler),
                                         ('/page', Page),
                                         ('/RemoveOld', RemoveOld)],
                                        debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
